<template>
  <!-- 操作按钮区域 -->
  <el-button plain type="primary" style="margin-bottom: 10px;" @click="Open()">添加</el-button>
  <!-- 批量删除按钮：当没有选中项时禁用，防止用户误操作 -->
  <el-button 
    plain 
    type="danger" 
    style="margin-bottom: 10px; margin-left: 10px;" 
    @click="batchDelete" 
    :disabled="multipleSelection.length === 0">
    批量删除
  </el-button>
  <el-button plain type="primary" style="float: right;" @click="Open()">导出</el-button>
  
  <!-- 数据表格：支持多选和批量操作 -->
  <el-table 
    :data="tableData" 
    border 
    style="width: 100%" 
    @selection-change="handleSelectionChange">
    <!-- 选择列：用于批量操作的复选框 -->
    <el-table-column type="selection" width="55" />
    <el-table-column fixed type="index" label="序号" width="60" />
    <el-table-column prop="workShopCode" label="车间编码" width="150" />
    <el-table-column prop="workShopName" label="车间名称" width="150" />
    <el-table-column prop="workShopDesc" label="车间描述" width="180" />
    <el-table-column prop="createrPeople" label="创建人" width="130" />
    <el-table-column prop="createTime" label="创建时间" width="180">
      <template #default="scope">
        {{ moment(scope.row.createTime).format('YYYY-MM-DD') }}
      </template>
    </el-table-column>
    <el-table-column prop="updateTime" label="修改时间" width="180">
      <template #default="scope">
        {{ moment(scope.row.updateTime).format('YYYY-MM-DD') }}
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" min-width="120">
      <template #default="scope">
        <el-button link  type="warning" @click="OpenUpdate(scope.row)">编辑</el-button>
        <el-button link  type="danger" @click="Del(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 添加车间弹窗 -->
  <el-dialog v-model="dialogVisible" title="添加车间" width="500px">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px">
      <el-form-item label="车间编码" prop="workShopCode">
        <el-input v-model="ruleForm.workShopCode" placeholder="请输入车间编码" />
      </el-form-item>
      <el-form-item label="车间名称" prop="workShopName">
        <el-input v-model="ruleForm.workShopName" placeholder="请输入车间名称" />
      </el-form-item>
      <el-form-item label="车间描述" prop="workShopDesc">
        <el-input v-model="ruleForm.workShopDesc" type="textarea" placeholder="请输入车间描述" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
      </span>
    </template>
  </el-dialog>
<!-- 修改车间弹窗 -->
  <el-dialog v-model="dialogVisibleUpdate" title="修改车间" width="500px">
    <el-form ref="ruleFormRef" :model="ruleFormUpdate" :rules="rules" label-width="120px">
      <el-form-item label="车间编码" prop="workShopCode">
        <el-input v-model="ruleFormUpdate.workShopCode" placeholder="请输入车间编码" />
      </el-form-item>
      <el-form-item label="车间名称" prop="workShopName">
        <el-input v-model="ruleFormUpdate.workShopName" placeholder="请输入车间名称" />
      </el-form-item>
      <el-form-item label="车间描述" prop="workShopDesc">
        <el-input v-model="ruleFormUpdate.workShopDesc" type="textarea" placeholder="请输入车间描述" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisibleUpdate = false">取消</el-button>
        <el-button type="primary" @click="submitFormUpdate(ruleFormRef)">确定</el-button>
      </span>
    </template>
  </el-dialog>
<!--分页-->
  <div class="pagination-container">
    <el-pagination
      v-model:current-page="page.PageIndex"
      v-model:page-size="page.PageSize"
      :page-sizes="[3, 6, 9, 12]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.totalcount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="custom-pagination"
    />
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import axios from 'axios';
import moment from 'moment';
import { ElMessage, ElMessageBox } from 'element-plus'
import { pa } from 'element-plus/es/locales.mjs';
import type { FormInstance, FormRules } from 'element-plus'
import { useCounterStore } from '@/stores/counter'
const pinia = useCounterStore();
const tableData = ref([]) // 表格数据
const multipleSelection = ref<any[]>([]) // 存储用户选中的表格行数据，用于批量操作
//车间向后端传参
const page = reactive({
  PageIndex: 1,
  PageSize: 5,
  totalcount: 0
})

//钩子
onMounted(() => {
  GetWorkShop()
})
//车间网络传出
const GetWorkShop = () => {
  axios.get('/api/FactoryModeling/GetWorkShop', { params: page }).then(res => {
    if (res.data.code == 200) {
      tableData.value = res.data.totalPage
      page.totalcount = res.data.totalcount
    }
  })
}

// 控制弹窗显示
const dialogVisible = ref(false);
const Open = () => {
  dialogVisible.value = true;
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  "workShopCode": "",
  "workShopName": "",
  "workShopDesc": "",
  "createrPeople": pinia.piniaDto.accountName
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
  workShopCode: [
    { required: true, message: '请输入车间编码', trigger: 'blur' },
  ],
  workShopName: [
    {
      required: true,
      message: '请输入车间名称',
      trigger: 'change',
    },
  ],
  workShopDesc: [
    {
      required: true,
      message: '请输入车间描述',
      trigger: 'change',
    }]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios.post('/api/FactoryModeling/AddWorkShop', ruleForm).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.message);
          ruleForm.workShopCode = '',

            dialogVisible.value = false;
          GetWorkShop(); // 提交成功后刷新表格数据
        } else {
          ElMessage.error(res.data.message)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  page.PageSize=val;
  GetWorkShop()
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  page.PageIndex=val;
  GetWorkShop()
}
const dialogVisibleUpdate = ref(false);
const OpenUpdate=(row:any)=>{
  dialogVisibleUpdate.value=true
  ruleFormUpdate.id=row.id
  ruleFormUpdate.workShopCode=row.workShopCode
  ruleFormUpdate.workShopName=row.workShopName
  ruleFormUpdate.workShopDesc=row.workShopDesc
}
const ruleFormUpdate = reactive({
  "id":null,
  "workShopCode": "",
  "workShopName": "",
  "workShopDesc": "",
  "updaterPeople": pinia.piniaDto.accountName
})
//修改网络
const submitFormUpdate = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios.put('/api/FactoryModeling/UpdateWorkShop', ruleFormUpdate).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.message);
            dialogVisibleUpdate.value = false;
          GetWorkShop(); // 提交成功后刷新表格数据
        } else {
          ElMessage.error(res.data.message)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
const Del=(id:any)=>{
  ElMessageBox.confirm(
    '确定要删除该车间吗？删除后数据将无法恢复。',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    axios.post(`/api/FactoryModeling/DelWorkShop`,{id:id}).then(res => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.message);
        GetWorkShop(); // 删除成功后刷新表格数据
      } else {
        ElMessage.error(res.data.message);
      }
    }).catch(error => {
      ElMessage.error('删除失败，请重试');
      console.error('Delete error:', error);
    });
  })
  .catch(() => {
    ElMessage.info('已取消删除');
  });
}

/**
 * 批量选择处理函数
 * 当用户在表格中选择/取消选择行时触发
 * @param val 当前选中的所有行数据数组
 */
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
}

/**
 * 批量删除功能
 * 删除用户选中的多条车间记录
 * 包含数据验证、用户确认、API调用、结果处理等完整流程
 */
const batchDelete = () => {
  // 1. 数据验证：检查是否有选中的数据
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的数据');
    return;
  }
  
  // 2. 提取选中行的ID数组，用于后端删除操作
  const ids = multipleSelection.value.map((item: any) => item.id);
  
  // 3. 显示确认对话框，防止用户误操作
  ElMessageBox.confirm(
    `确定要删除选中的 ${multipleSelection.value.length} 条车间记录吗？删除后数据将无法恢复。`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning', // 警告类型的对话框
    }
  )
  .then(() => {
    // 4. 用户确认删除，调用后端批量删除接口
    axios.post('/api/FactoryModeling/DelWorkShop', {
      id: 0,        // 单个删除时使用，批量删除时设为0
      ids: ids      // 要删除的ID数组
    }).then(res => {
      // 5. 处理删除结果
      if (res.data.code == 200) {
        // 删除成功
        ElMessage.success(res.data.message);
        GetWorkShop(); // 重新获取数据，刷新表格显示
        multipleSelection.value = []; // 清空选择状态，重置UI
      } else {
        // 删除失败，显示服务器返回的错误信息
        ElMessage.error(res.data.message);
      }
    }).catch(error => {
      // 6. 处理网络错误或其他异常
      ElMessage.error('批量删除失败，请重试');
      console.error('Batch delete error:', error);
    });
  })
  .catch(() => {
    // 7. 用户取消删除操作
    ElMessage.info('已取消批量删除');
  });
}
</script>

<style scoped>
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 10px;
  background-color: #f9fafb;
  border-radius: 8px;
}

.custom-pagination {
  --el-pagination-item-size: 32px;
  --el-pagination-item-bg: #ffffff;
  --el-pagination-item-color: #606266;
  --el-pagination-item-hover-color: #4096ff;
  --el-pagination-item-active-color: #ffffff;
  --el-pagination-item-active-bg: #4096ff;
  --el-pagination-border-radius: 6px;
  --el-pagination-margin: 0 5px;
}

.custom-pagination .el-pagination__prev, .custom-pagination .el-pagination__next {
  width: 32px;
  height: 32px;
  border-radius: 6px;
}

.custom-pagination .el-pagination__sizes {
  margin-right: 10px;
}

.custom-pagination .el-pagination__total {
  margin-right: 10px;
  color: #606266;
}

.custom-pagination .el-pagination__item {
  margin: 0 5px;
  border-radius: 6px;
  min-width: 32px;
  height: 32px;
  line-height: 32px;
}

.custom-pagination .el-pagination__item:hover {
  background-color: #f0f5ff;
}

.custom-pagination .el-pagination__item.is-active {
  background-color: #4096ff;
  color: #ffffff;
}
</style>
